package com.breaktian.assemble.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author breaktian
 * udp协议
 * 
 * */
public class UdpSocket {
	
	private DatagramSocket udpSocket;
	private String remoteIp;
	private int remotePort;

	/**
	 * 随机分配一个端口
	 * */
	public UdpSocket(){
		try {
			udpSocket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	
	public UdpSocket(int port){
		try {
			udpSocket = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 连接
	 * */
	public UdpSocket connect(String remoteIp, int remotePort){
		this.remoteIp = remoteIp;
		this.remotePort = remotePort;
		return this;
	}
	
	/**
	 * 发送数据
	 * */
	public void send(String s){
		if(udpSocket==null) throw new IllegalStateException("udpSocket为null");
		try {
			byte[] sendData = s.getBytes();
			DatagramPacket packet = new DatagramPacket(sendData, sendData.length,  InetAddress.getByName(remoteIp), remotePort);
			udpSocket.send(packet);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 发送数据
	 * */
	public void send(byte[] data){
		if(udpSocket==null) throw new IllegalStateException("udpSocket为null");
		try {
			DatagramPacket packet = new DatagramPacket(data, data.length,  InetAddress.getByName(remoteIp), remotePort);
			udpSocket.send(packet);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 关闭socket
	 * */
	public void close(){
		if(udpSocket==null) throw new IllegalStateException("udpSocket为null");
		udpSocket.close();
	}
	
}
